package com.bms.cfcmms.util;

import com.bms.cfcmms.util.annotation.OperationLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * Created by carl on 2017/3/19.
 */
@Component
@Aspect
public class OperationLogAspect {

    private  static  final Logger log = LoggerFactory.getLogger(OperationLogAspect. class);

    //Controller层切点
    @Pointcut("@annotation(com.bms.cfcmms.util.annotation.OperationLog)")
    public  void controllerAspect() {
        log.info("@annotation(OperationLog)");
    }

    @Around("controllerAspect()")
    public Object doAround(ProceedingJoinPoint joinPoint) {

        Object retVal = null;
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        OperationLog operationLog = method.getAnnotation(OperationLog.class);
        SpringUtils.getMessage(operationLog.description());
        try {
            retVal = joinPoint.proceed();
        } catch (Throwable throwable) {
            retVal = new ActionResult();
            log.error("", throwable);
        }
        ServletRequestAttributes requestAtts = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAtts.getRequest();

        if (retVal instanceof ActionResult) {
            ActionResult actionResult = (ActionResult)retVal;
            String success = actionResult.getSuccess() ? "成功" : "失败";
            log.info("操作结果为：" + success);
            log.info("操作详细描述为：" + actionResult.getMsg());
        } else {
            //TODO
        }
        log.info("客户端IP地址为：" + request.getRemoteAddr());
        return retVal;
    }
}
